import { injectable, inject } from "inversify";
import { User } from "./user.dto";
import { PrismaDB } from "../db";
import { plainToClass } from "class-transformer";
import { validate } from "class-validator";

// @injectable 表示一个注射器，可以注入到其他类中
@injectable()
export class UserService {
  // 自动注入prisma
  constructor(@inject(PrismaDB) private PrismaDB: PrismaDB) {}

  /**
   * 查询所有用户信息
   */
  public async getAllUser() {
    return await this.PrismaDB.prisma.user.findMany();
  }

  /**
   * 添加用户信息
   */
  public async addUser(user: User) {
    let userDto = plainToClass(User, user);
    let error = await validate(userDto);
    if (error.length > 0) {
      return error; // 如果有错误，返回错误信息
    } else {
      return await this.PrismaDB.prisma.user.create({
        data: user,
      });
    }
  }
}
